package feeinterface.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.ulwx.database.DataBaseSet;
import com.ulwx.database.RowMapper;
import com.ulwx.tool.DbUtils;
import feeinterface.modeldb.ChannelOnlyUseOnceForImsi;

/**
 * 针对一个用户只能终身使用一次的通道记录表
 * 
 * @author 黄杰
 * 
 */
public class ChannelOnlyUseOnceForImsiDao {

	private static final Logger log = Logger
			.getLogger(ChannelOnlyUseOnceForImsi.class);

	/**
	 * 获取该用户使用过的通道
	 * 
	 * @param IMSI
	 * @return
	 */
	public static List<Integer> getUseOneChannel(String IMSI) {
		String sql = "SELECT ChannelID FROM ChannelOnlyUseOnceForImsi a WHERE a.Imsi=?" +
				" UNION  " +
				"  SELECT b.ParentChannelID FROM ChannelOnlyUseOnceForImsi a," +
				"  Channel b WHERE a.channelid=b.channelsno " +
				"   AND b.ParentChannelID>0 AND a.Imsi=? " +
				" UNION" +
				"   SELECT c.channelsno FROM ChannelOnlyUseOnceForImsi a, " +
				"  Channel b, Channel c WHERE a.channelid=b.channelsno AND" +
				"  b.channelsno=c.ParentChannelID  AND a.Imsi=? ";
		
		Map<Integer, Object> args = new HashMap<Integer, Object>();
		try {
			args.put(1, IMSI);
			args.put(2, IMSI);
			args.put(3, IMSI);
			RowMapper<Integer> rowMapper = new RowMapper<Integer>() {
				public Integer mapRow(DataBaseSet rs) throws Exception {
					return rs.getInt("ChannelID");
				}
			};
			List<Integer> list = DbUtils.doQueryObject(null, sql, args,
					rowMapper);
			if (list != null && list.size() > 0) {
				return list;
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return new ArrayList<Integer>();
	}

	/**
	 * 保存用户通道使用
	 * @param coufi
	 */
	public static void InsertOrUpdate(ChannelOnlyUseOnceForImsi couofi) {
		try {
			String sql = "INSERT INTO ChannelOnlyUseOnceForImsi (Imsi,ChannelID,UpdateTime)"
					+ " VALUES (?,?,?) ON DUPLICATE KEY UPDATE UpdateTime=?";
			Map<Integer, Object> map = new HashMap<Integer, Object>();
			map.put(1, couofi.getImsi());
			map.put(2, couofi.getChannelID());
			map.put(3, couofi.getUpdateTime());
			map.put(4, couofi.getUpdateTime());
			DbUtils.executeBindUpdate(null, sql, map);
		} catch (Exception e) {
			log.error("", e);

		}
	}
	
	public static void main(String[] args) {
		System.out.println(getUseOneChannel("460021275054553"));
		
	}
}
